package huffmann;

import java.io.*;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

public class Arquivo {
	private File file;
	private FileReader fileReader;
	private BufferedReader bufferedReader;

	public File getFile() {
		return this.file;
	}
	
	public void setFile(File file) {
		file = file;
	}

	public void openFile(){
/*		JFileChooser fileChooser = new JFileChooser();

		fileChooser.setFileSelectionMode(
		      JFileChooser.FILES_AND_DIRECTORIES );
		setFile(fileChooser.getSelectedFile());
		int result = fileChooser.showOpenDialog(fileChooser);
		if (result == JFileChooser.CANCEL_OPTION)
			System.exit( 1 );
		file = fileChooser.getSelectedFile();
*/
		file = new File("lcet10.txt");
		if (file.exists()){
			try {
				fileReader = new FileReader(file);
				bufferedReader = new BufferedReader(fileReader);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
/*		else{
			JOptionPane.showMessageDialog(fileChooser, "Invalid File Name",
					"Invalid File Name", JOptionPane.ERROR_MESSAGE );
			System.exit( 1 );
		}
*/
	}

	public void reopenFile(){
		if (file != null)
			try {
				fileReader = new FileReader(file);
				bufferedReader = new BufferedReader(fileReader);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
	}

	public void read(Objeto v[]){
		String line = null;

		try{
			while( (line = bufferedReader.readLine()) != null ){
				for (int i = 0; i < line.length(); i++) {
					int n = line.charAt(i);
					
					if (v[n] == null){
						v[n] = new Objeto();
					}
					v[n].setOcorrencias(v[n].getOcorrencias() + 1);
					v[n].setAscii(n);
				}
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public String read(){
		String line = null;

		try{
			line = bufferedReader.readLine();
		}catch(Exception e) {
			e.printStackTrace();
		}
		return line;
	}

	public void closeFile(){
		try{
			bufferedReader.close();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}
